package com.tjrac.generalpermissions.service.impl;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import com.tjrac.filter.entity.Verification;
import com.tjrac.filter.stereotype.PermissionControl;
import com.tjrac.generalpermissions.dao.PermissionDao;
import com.tjrac.generalpermissions.dao.RoleDao;
import com.tjrac.generalpermissions.dao.RolePermissionDao;
import com.tjrac.generalpermissions.domain.Permission;
import com.tjrac.generalpermissions.domain.Role;
import com.tjrac.generalpermissions.domain.RolePermission;
import com.tjrac.generalpermissions.epception.MsgException;
import com.tjrac.generalpermissions.epception.statusCode.RoleCode;
import com.tjrac.generalpermissions.epception.statusCode.VerificationCode;
import com.tjrac.generalpermissions.service.RoleService;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author ZeNing
 * @create 2020-11-29 15:19
 */
@Service
@Transactional
public class RoleServiceImpl implements RoleService {

    @Resource
    RoleDao roleDao;

    @Resource
    RolePermissionDao rolePermissionDao;


    @PermissionControl("查询角色")
    @Override
    public Role queryById(int id) throws MsgException {

        Role role = roleDao.queryById(id);
        if (role == null) {
            throw new MsgException(RoleCode.NOT_EXIST_ROLE, "该角色不存在,查询失败");
        }

        return role;
    }

    @PermissionControl("查询所有角色")
    @Override
    public String queryAllRole() throws MsgException {
        List<Role> roles = roleDao.queryAll();
        if (roles == null) {
            throw new MsgException(RoleCode.FAILURE_SELECT_ALL, "查询所有角色失败");
        } else {
            return new MsgException(RoleCode.SUCCESS_ROLE, "查询所有角色成功").toListJson(roles);
        }
    }

    @PermissionControl("添加角色")
    @Override
    public String addRole(Role role) throws MsgException {
        if (roleDao.queryByName(role.getName()) != null) {
            throw new MsgException(RoleCode.EXIST_ROLE, "角色已存在，添加失败");
        } else {
            if (roleDao.addRole(role) != 0) {
                return new MsgException(RoleCode.SUCCESS_ROLE, "添加角色成功").toJson();
            } else {
                throw new MsgException(RoleCode.FAILURE_ADD, "添加角色失败");
            }
        }

    }

    @PermissionControl("删除角色")
    @Override
    public String delRole(int id) throws MsgException{
        try {
            if (roleDao.queryById(id) == null) {
                throw new MsgException(RoleCode.NOT_EXIST_ROLE, "角色不存在，删除失败");
            } else {
                List<RolePermission> rolePermissions = rolePermissionDao.queryByRid(id);
                if (rolePermissions != null) {
                    for (RolePermission rp : rolePermissions) {
                        rolePermissionDao.delRolePermission(rp.getId());
                    }
                }
                if (roleDao.delRole(id) != 0) {
                    //删除角色的同时,将权限角色映射表中该拥有该角色的行全部删除

                    return new MsgException(RoleCode.SUCCESS_ROLE, "删除角色成功").toJson();
                } else {
                    throw new MsgException(RoleCode.FAILURE_DEL, "删除角色失败");
                }
            }
        } catch (DataIntegrityViolationException e){
            Throwable cause = e.getCause();
            if (cause instanceof MySQLIntegrityConstraintViolationException) {
                throw new MsgException(RoleCode.USER_FAILURE_DEL, "有用户被赋予该角色删除失败");
            }
            throw new MsgException(VerificationCode.UNKNOWN_ERROR, "未知数据异常");
        }
    }

    @PermissionControl("修改角色")
    @Override
    public String modifyRole(Role role, Integer[] pid) throws MsgException {
        int rid = role.getId();
        if (roleDao.queryById(role.getId()) == null) {
            throw new MsgException(RoleCode.NOT_EXIST_ROLE, "角色不存在,修改失败");
        } else {
            if (roleDao.modifyById(role) != 0) {
                /*修改角色权限*/
                Role ole_role = roleDao.queryById(rid);
                List<Verification> permissions = ole_role.getPermissions();

                List<Integer> del_permissions = new CopyOnWriteArrayList<>();
                List<Integer> add_permissions = new ArrayList<>();
                for (Verification v : permissions){
                    del_permissions.add(v.getId());
                }
                for (Integer p : pid){
                    boolean exist = false;
                    for (Integer d : del_permissions){
                        if (Objects.equals(p, d)){
                            del_permissions.remove(p);
                            exist = true;
                            break;
                        }
                    }
                    if (!exist){
                        add_permissions.add(p);
                    }
                }
                /*新增角色权限*/
                for (int add : add_permissions){
                    rolePermissionDao.addRolePermissionByRP(rid, add);
                }
                /*删除角色权限*/
                for (int del : del_permissions){
                    rolePermissionDao.delRolePermissionByRP(rid, del);
                }


                return new MsgException(RoleCode.SUCCESS_ROLE, "修改角色成功").toJson();
            } else {
                throw new MsgException(RoleCode.FAILURE_UPD, "修改角色失败");
            }
        }
    }

}
